package net.expectx.micro.shop.api.controller;

import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.ResultCollectors;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import io.swagger.annotations.*;

import net.expectx.common.single.base.BaseConstants;
import net.expectx.common.single.base.BaseResult;
import net.expectx.common.single.base.BaseResultConstants;
import net.expectx.common.single.util.*;
import net.expectx.micro.shop.api.authorization.annotation.Authorization;
import net.expectx.micro.shop.api.common.ApiConstants;
import net.expectx.micro.shop.api.common.ApiResult;
import net.expectx.micro.shop.api.common.ApiResultConstants;
import net.expectx.micro.shop.api.common.util.ApiUtils;
import net.expectx.micro.shop.api.manager.RedisTokenSingle;
import net.expectx.micro.shop.api.validator.NotNullValidator;
import net.expectx.micro.shop.dao.bean.MemberUser;
import net.expectx.micro.shop.dao.bean.MemberUserDetails;
import net.expectx.micro.shop.dao.bean.MemberUserExample;
import net.expectx.micro.shop.rpc.api.MemberUserDetailsService;
import net.expectx.micro.shop.rpc.api.MemberUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author lijian
 */
@Api(description = "会员相关接口", tags = "会员")
@Controller
@RequestMapping("/member")
public class MemberUserController {
    @Autowired
    private MemberUserService memberUserService;
    @Autowired
    private MemberUserDetailsService memberUserDetailsService;
    static Pattern p = Pattern.compile("^1[3|4|5|6|7|8][0-9]\\d{4,8}$");


    @ApiOperation(value = "登陆(不需)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "手机号", defaultValue = "18363003321", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "password", value = "密码", defaultValue = "94:87:e0:0e:6a:9a", required = true, dataType = "String", paramType = "query")

    })
    @ApiResponses({
            @ApiResponse(code = 0, message = "失败"),
            @ApiResponse(code = 200, message = "成功"),
            @ApiResponse(code = 500, message = "系统异常"),
            @ApiResponse(code = 501, message = "参数检查失败"),
            @ApiResponse(code = 502, message = "令牌失效，请重新登录"),
            @ApiResponse(code = 504, message = "缺少消息头MAC地址或为空"),
            @ApiResponse(code = 505, message = "缺少消息头User-Agent地址或为空"),
            @ApiResponse(code = 506, message = "缺少消息头App-Key和App-Secret参数或为空"),
            @ApiResponse(code = 506001, message = "无效的App-Key"),
            @ApiResponse(code = 506002, message = "无效的App-Secret"),
    })
    @PostMapping("login")
    public ResponseEntity<ApiResult> login(
            @RequestParam(required = true, value = "username") String username,
            @RequestParam(required = true, value = "password") String password,
            HttpServletRequest request) throws Exception {

        // 参数检查
        FluentValidator fluentValidator = FluentValidator.checkAll();

        if (Strings.isNullOrEmpty(username)) {
            fluentValidator.on(username, new NotNullValidator("手机号"));
        }
        if (Strings.isNullOrEmpty(password)) {
            fluentValidator.on(password, new NotNullValidator("密码"));
        }
        ComplexResult result = fluentValidator.doValidate().result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new ResponseEntity<>(new ApiResult(false, ApiResultConstants.PARAM_CHECK_FAILED, result.getErrors()), HttpStatus.OK);
        }
        Matcher m = p.matcher(username);
        if (!m.matches()) {
            return new ResponseEntity<>(new ApiResult(Boolean.FALSE, 0, "请输入正确的手机号", null), HttpStatus.OK);
        }
        //实现代码
        MemberUserExample memberUserExample = new MemberUserExample();
        memberUserExample.createCriteria().andUserNameEqualTo(username);
        List<MemberUser> memberUsers = memberUserService.selectByExample(memberUserExample);

        if (memberUsers.isEmpty()) {
            return new ResponseEntity<>(new ApiResult(false, ApiResultConstants.USER_IS_EXIST_NO, null), HttpStatus.OK);
        }
        MemberUser memberUser = memberUsers.get(0);
        if (!Strings.isNullOrEmpty(password)) {
            password = Md5Util.md5(password + memberUser.getSalt());
            if (!password.equals(memberUser.getPassword())) {
                return new ResponseEntity<>(new ApiResult(false,ApiResultConstants.ERROR_USER_PASSWORD, null), HttpStatus.OK);
            }
        }
        String accessToken = TokenUtil.getRandomToken();

        // redis保存令牌
        RedisTokenSingle.getInstance().tokenManager().createRelationship(memberUser.getId().toString(), accessToken);
        Map<String, Object> exampleMap = new HashMap<>(16);
        exampleMap.put("accessToken", accessToken);
        return new ResponseEntity<>(new ApiResult(Boolean.TRUE, ApiResultConstants.SUCCESS, accessToken), HttpStatus.OK);
    }
    @ApiOperation(value = "注册")
    @PostMapping("register")
    public ResponseEntity<ApiResult> register(
            @RequestParam(required = false, value = "username") String username,
            @RequestParam(required = false, value = "password") String password,
            HttpServletRequest request) {
        // 参数检查
        FluentValidator fluentValidator = FluentValidator.checkAll();

        if (Strings.isNullOrEmpty(username)) {
            fluentValidator.on(username, new NotNullValidator("手机号"));
        }
        if (Strings.isNullOrEmpty(password)) {
            fluentValidator.on(password, new NotNullValidator("密码"));
        }
        ComplexResult result = fluentValidator.doValidate().result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new ResponseEntity<>(new ApiResult(false, ApiResultConstants.PARAM_CHECK_FAILED, result.getErrors()), HttpStatus.OK);
        }
        Matcher m = p.matcher(username);
        if (!m.matches()) {
            return new ResponseEntity<>(new ApiResult(Boolean.FALSE, 0, "请输入正确的手机号", null), HttpStatus.OK);
        }

        MemberUserExample memberUserExample = new MemberUserExample();
        memberUserExample.createCriteria().andUserNameEqualTo(username);
        List<MemberUser> memberUsers = memberUserService.selectByExample(memberUserExample);
        if (!memberUsers.isEmpty()) {
            return new ResponseEntity<>(new ApiResult(false, ApiResultConstants.PHONE_IS_EXIST_YES, null), HttpStatus.OK);
        }


        MemberUser memberUser = new MemberUser();
        memberUser.setSource(Byte.valueOf("1"));
        MemberUserDetails memberUserDetails = new MemberUserDetails();
        memberUser.setUserName(username);

        /**
         * 加密md5盐值
         */
        memberUser.setSalt(UUID.randomUUID().toString().toLowerCase().replace("-", ""));
        /**
         * 加密后的密码
         */
        memberUser.setPassword(Md5Util.md5(password + memberUser.getSalt()));
        memberUser.setGmtCreate(System.currentTimeMillis());
        memberUser.setGmtModified(System.currentTimeMillis());
        memberUser.setLastLoginTime(System.currentTimeMillis());
        memberUser.setAvatar("");
        memberUser.setIsDeleted(BaseConstants.NO);
        BaseResult baseResult = memberUserService.insertSelective(memberUser);
        if (baseResult.isSuccess()) {
            MemberUser newMemberUser = (MemberUser) baseResult.getData();
            memberUserDetails.setUserId(newMemberUser.getId());
            memberUserDetails.setInvitationCode(ShareCodeUtil.generateSerialCode(newMemberUser.getId()));
            memberUserDetails.setGmtCreate(System.currentTimeMillis());
            memberUserDetails.setGmtModified(System.currentTimeMillis());
            memberUserDetails.setIsDeleted(BaseConstants.NO);
            baseResult = memberUserDetailsService.insertSelective(memberUserDetails);
        }
        return new ResponseEntity<>(new ApiResult(baseResult), HttpStatus.OK);


    }

    /**
     * 注销登录
     *
     * @return
     */
    @ApiOperation(value = "注销登录(需)")
    @ApiResponses({
            @ApiResponse(code = 0, message = "失败"),
            @ApiResponse(code = 200, message = "成功"),
            @ApiResponse(code = 500, message = "系统异常"),
            @ApiResponse(code = 502, message = "令牌失效，请重新登录"),
            @ApiResponse(code = 504, message = "缺少消息头MAC地址或为空"),
            @ApiResponse(code = 505, message = "缺少消息头User-Agent地址或为空"),
            @ApiResponse(code = 506, message = "缺少消息头App-Key和App-Secret参数或为空"),
            @ApiResponse(code = 506001, message = "无效的App-Key"),
            @ApiResponse(code = 506002, message = "无效的App-Secret"),
    })
    @PostMapping("/logout")
    @Authorization
    public ResponseEntity<ApiResult> logout(HttpServletRequest request) throws Exception {
        Long userId = ApiUtils.getUserId(request);
        if (userId == -1) {
            return new ResponseEntity<>(new ApiResult(false, ApiResultConstants.ERROR_UNAUTHORIZED, null), HttpStatus.OK);
        }

        try {
            RedisTokenSingle.getInstance().tokenManager().delRelationshipByKey(userId.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(new ApiResult(Boolean.TRUE, ApiResultConstants.SUCCESS, null), HttpStatus.OK);
        }
        return new ResponseEntity<>(new ApiResult(Boolean.TRUE, ApiResultConstants.SUCCESS, null), HttpStatus.OK);

    }







    @ApiOperation(value = "修改个人信息(需)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "avatar", value = "头像", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "signaturen", value = "用户昵称", required = true, dataType = "String", paramType = "query"),
    })
    @ApiResponses({
            @ApiResponse(code = 0, message = "失败"),
            @ApiResponse(code = 200, message = "成功"),
            @ApiResponse(code = 500, message = "系统异常"),
            @ApiResponse(code = 501, message = "参数检查失败"),
            @ApiResponse(code = 502, message = "令牌失效，请重新登录"),
            @ApiResponse(code = 504, message = "缺少消息头MAC地址或为空"),
            @ApiResponse(code = 505, message = "缺少消息头User-Agent地址或为空"),
            @ApiResponse(code = 506, message = "缺少消息头App-Key和App-Secret参数或为空"),
            @ApiResponse(code = 506001, message = "无效的App-Key"),
            @ApiResponse(code = 506002, message = "无效的App-Secret"),
            @ApiResponse(code = 50022, message = "数据更新异常"),
            @ApiResponse(code = 50020, message = "暂无数据"),
    })
    @RequestMapping(value = "modifyUserInfo", method = RequestMethod.POST)
    @Authorization
    public ResponseEntity<ApiResult> modifyUserInfo(
            @RequestParam(required = true, value = "avatar") String avatar,
            @RequestParam(required = true, value = "signaturen") String signaturen,
            HttpServletRequest request) throws Exception {
        Long userId = ApiUtils.getUserId(request);
        if (userId == -1) {
            return new ResponseEntity<>(new ApiResult(false, ApiResultConstants.ERROR_UNAUTHORIZED, null), HttpStatus.OK);
        }
        MemberUser memberUser = memberUserService.selectByPrimaryKey(userId);
        MemberUserDetails memberUserDetails = memberUser.getMemberUserDetails();
        if (!Strings.isNullOrEmpty(avatar)) {
            memberUser.setAvatar(avatar);
        }
        if (!Strings.isNullOrEmpty(signaturen)) {
            memberUserDetails.setSignature(signaturen);
        }
        BaseResult baseResult = memberUserService.updateByPrimaryKeySelective(memberUser);
        memberUserDetailsService.updateByPrimaryKeySelective(memberUserDetails);
        return new ResponseEntity<>(new ApiResult(baseResult), HttpStatus.OK);
    }

    @ApiOperation(value = "获取当前个人信息(需)")
    @ApiImplicitParams({
    })
    @ApiResponses({
            @ApiResponse(code = 0, message = "失败"),
            @ApiResponse(code = 200, message = "成功"),
            @ApiResponse(code = 500, message = "系统异常"),
            @ApiResponse(code = 501, message = "参数检查失败"),
            @ApiResponse(code = 502, message = "令牌失效，请重新登录"),
            @ApiResponse(code = 504, message = "缺少消息头MAC地址或为空"),
            @ApiResponse(code = 505, message = "缺少消息头User-Agent地址或为空"),
            @ApiResponse(code = 506, message = "缺少消息头App-Key和App-Secret参数或为空"),
            @ApiResponse(code = 506001, message = "无效的App-Key"),
            @ApiResponse(code = 506002, message = "无效的App-Secret"),
            @ApiResponse(code = 50020, message = "暂无数据"),
    })
    @RequestMapping(value = "userInfo", method = RequestMethod.GET)
    @Authorization
    public ResponseEntity<ApiResult> modifyUserInfo(
            HttpServletRequest request) throws Exception {

        Long userId = ApiUtils.getUserId(request);
        if (userId == -1) {
            return new ResponseEntity<>(new ApiResult(false, ApiResultConstants.ERROR_UNAUTHORIZED, null), HttpStatus.OK);
        }
        MemberUser memberUser = memberUserService.selectByPrimaryKey(userId);
        return new ResponseEntity<>(new ApiResult(Boolean.TRUE, ApiResultConstants.SUCCESS, memberUser), HttpStatus.OK);


    }



}
